﻿using AntUnion.FrameWork.Model.Models;
using AntUnion.FrameWork.Util;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using AntUnion.FrameWork.Web.Common;

namespace AntUnion.FrameWork.Web.Areas.Console.Controllers
{
    [Area("Console")]
    public class CRMWalletController : BaseController
    {
        private readonly IWebHostEnvironment _hostingEnv;
        private readonly mtContext _context;

        public CRMWalletController(mtContext context, IWebHostEnvironment hostingEnv) : base(context, hostingEnv)
        {
            _context = context;
            _hostingEnv = hostingEnv;
        }

        public IActionResult Index()
        {
            return View();
        }

        #region 账户列表
        /// <summary>
        /// 获取账户列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<JsonResult> GetListJson(int page, int limit, int crmId = 0, string nameOrAccount = "", long? MT5Account = null)
        {
            //nameOrAccount: $("#nameOrAccount").val(),
            //                MT5Account: $("#MT5Account").val()
            ListResult res = new ListResult();
            try
            {
                var data = from y in _context.CrmWallets
                           join c in _context.CrmUsers on y.CrmId equals c.Id
                           join m in _context.Mt5Users on c.Id equals m.CrmId into cc
                           from ccdata in cc.DefaultIfEmpty()
                           select new
                           {
                               id = y.Id,
                               crmId = y.CrmId,
                               currency = y.Currency,
                               email = c.Email,
                               fullName = c.Name,
                               loginName = c.LoginName,
                               tradingAccount = ccdata == null ? null : (long?)ccdata.Login,
                               balance = y.Balance.ToString("#,##0.00"),
                               totalDeposit = _context.CrmDeposits.Where(k => k.CrmId == y.CrmId).Sum(k => k.DepositAmount).ToString("#,##0.00"),
                               totalWithdrawal = _context.CrmWithdrawals.Where(k => k.CrmId == y.CrmId).Sum(k => k.FromAmount).ToString("#,##0.00"),
                               createDate = y.CreateDate
                           };
                if (crmId != 0)
                {
                    data = data.Where(k => k.crmId == crmId);
                }
                if (!string.IsNullOrEmpty(nameOrAccount))
                {
                    data = data.Where(k => k.fullName.Contains(nameOrAccount) || k.loginName.Contains(nameOrAccount));
                }
                if (MT5Account != null)
                {
                    data = data.Where(k => k.tradingAccount == MT5Account);
                }
                res.Data = await data.OrderBy(k => k.id).Skip((page - 1) * limit).Take(limit).ToArrayAsync();
                res.Code = 0;
                res.Count = data.Count();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion


        #region 调整账户余额
        /// <summary>
        /// 调整账户余额
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns></returns>
        public IActionResult BalanceAdjustment(string idList)
        {
            ViewBag.idList = idList;
            return View();
        }

        /// <summary>
        /// 批量调整账户余额
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost, ActionName("EditBalanceAdjustmentItems")]
        public async Task<IActionResult> EditBalanceAdjustmentItems(string idList, int operationType, decimal price, string remark)
        {
            Result res = new Result();
            try
            {
                CrmWallet model = await _context.CrmWallets.FindAsync(idList);
                CrmUser crmUser = _context.CrmUsers.Where(k => k.Id == model.CrmId).FirstOrDefault();
                CrmWalletTransaction transaction = new CrmWalletTransaction
                {
                    Id = CommonHelper.GetOrderNo(),
                    WalletId = model.Id,
                    BeforeAmount = model.Balance,
                    Creator = User.LoginName,
                    CreateDate = DateTime.Now,
                };
                if (operationType == 0)
                {
                    transaction.Amount = price;
                    transaction.AfterAmount = model.Balance + price;
                    model.Balance = model.Balance + price;
                    transaction.Type = "cashDeposit";
                    transaction.Mode = "systemDeposit";
                }
                else
                {
                    transaction.Amount = price * -1;
                    transaction.AfterAmount = model.Balance - price;
                    model.Balance = model.Balance - price;
                    transaction.Type = "cashOut";
                    transaction.Mode = "systemWithdrawal";
                }
                transaction.Remark = remark;
                if (model.Balance < 0)
                {
                    res.Code = 1;
                    res.Msg = "insufficientFunds";
                    return new JsonResult(res);
                }
                _context.CrmWalletTransactions.Add(transaction);
                res.Code = 0;
                res.Msg = $"{transaction.Type}Success";
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = $"submitFail";
                res.Data = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion
    }
}
